package asionreachel.cn.smarthomedemo.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import asionreachel.cn.smarthomedemo.R;
import asionreachel.cn.smarthomedemo.base.BaseActivity;
import asionreachel.cn.smarthomedemo.base.BaseDevice;
import asionreachel.cn.smarthomedemo.base.Common;
import familyclient.android.device.cdm1.JDevice_CDM1Interface;
import familyclient.android.device.cdm1.JDevice_CDM1Listener;
import familyclient.android.familymanager.JFamilyManagerInterface;
import familyclient.android.familymanager.JFamilyManagerListener;
import familyclient.java.familymanager.data.JFamilyInfoData;

public class ShareListActivity extends BaseActivity {
    private static final String FUNCTION = "ShareList";

    private static final int ALERT_DIALOG_DEL_SHARE = 0;
    private static final int ALERT_DIALOG_CLEAR_ALL = 1;

    private String m_strDeviceID = "";
    private String m_strFamilyID = "";
    private String m_strDeviceName = "";

    private String m_strWaitSharePhone = "";
    private String m_strWaitShareEmail = "";

    private JFamilyInfoData m_dataMasterFamilyInfo = new JFamilyInfoData();

    private class JShareInfoData {
        String m_strShareFamilyID = "";
        int m_iShareValue = 0;
        String m_strShareFamilyName = "";
        int m_iShareFamilySex = JFamilyInfoData.s_iSex_Unknow;
        String m_strShareFamilyPhone = "";
        String m_strShareFamilyEmail = "";
    }

    ;

    private class JShareInfoListData {
        private final ArrayList<JShareInfoData> m_listData = new ArrayList<JShareInfoData>();

        public JShareInfoListData() {
        }

        public void AddData(final JShareInfoData a_dataShareInfo) {
            for (int iIndex = 0; iIndex < m_listData.size(); ++iIndex) {
                if (a_dataShareInfo.m_strShareFamilyID.equals(m_listData.get(iIndex).m_strShareFamilyID)) {
                    m_listData.set(iIndex, a_dataShareInfo);
                    return;
                }
            }

            m_listData.add(a_dataShareInfo);
        }

        public void DelData(final String a_strShareFamilyID) {
            for (int iIndex = 0; iIndex < m_listData.size(); ++iIndex) {
                if (a_strShareFamilyID.equals(m_listData.get(iIndex).m_strShareFamilyID)) {
                    m_listData.remove(iIndex);
                    return;
                }
            }
        }

        public JShareInfoData GetData(int a_iIndex) {
            return m_listData.get(a_iIndex);
        }

        public JShareInfoData GetData(String a_strShareFamilyID) {
            for (int iIndex = 0; iIndex < m_listData.size(); ++iIndex) {
                if (a_strShareFamilyID.equals(m_listData.get(iIndex).m_strShareFamilyID))
                    return m_listData.get(iIndex);
            }
            return null;
        }

        public int GetSize() {
            return m_listData.size();
        }
    }

    private JShareInfoListData m_listShareInfo = new JShareInfoListData();

    private JFamilyManagerListener m_listenerFamilyManager = new JFamilyManagerListener() {
        @Override
        public void GetFamilyInfoByIDCb(JFamilyInfoData a_dataFamilyInfo, String a_strErr) {
            if (!m_bRun)
                return;

            if (null != a_strErr && a_strErr.length() > 0) {
                Common.showToast(Common.MakeMsgByErr(FUNCTION, a_strErr));
            } else {
                JShareInfoData dataShareInfo = m_listShareInfo.GetData(a_dataFamilyInfo.m_strFamilyID);
                if (null != dataShareInfo) {
                    dataShareInfo.m_strShareFamilyName = a_dataFamilyInfo.m_strFamilyName;
                    dataShareInfo.m_iShareFamilySex = a_dataFamilyInfo.m_iSex;
                    dataShareInfo.m_strShareFamilyPhone = a_dataFamilyInfo.m_strPhone;
                    dataShareInfo.m_strShareFamilyEmail = a_dataFamilyInfo.m_strEmail;
                }
                if (m_strWaitSharePhone.length() > 0 && m_strWaitSharePhone.equals(a_dataFamilyInfo.m_strPhone)) {
                    BaseDevice.SetShareInfo(m_strDeviceID, a_dataFamilyInfo.m_strFamilyID, 100);
                    m_strWaitSharePhone = "";
                } else if (m_strWaitShareEmail.length() > 0 && m_strWaitShareEmail.equals(a_dataFamilyInfo.m_strEmail)) {
                    BaseDevice.SetShareInfo(m_strDeviceID, a_dataFamilyInfo.m_strFamilyID, 100);
                    m_strWaitShareEmail = "";
                }
                if (m_strFamilyID.equals(a_dataFamilyInfo.m_strFamilyID))
                    m_dataMasterFamilyInfo = a_dataFamilyInfo;
                UpdateView();
            }
        }
    };

    private JDevice_CDM1Listener m_listenerCDM1 = new JDevice_CDM1Listener() {
        @Override
        public void CbDeviceInfoUpdatedCb(String a_strDeviceID) {
            if (m_bRun && m_strDeviceID.equals(a_strDeviceID))
                JDevice_CDM1Interface.GetInstance().GetDeviceInfo(a_strDeviceID);
        }

        @Override
        public void CbDeviceInfoListUpdatedCb() {
            if (m_bRun)
                JDevice_CDM1Interface.GetInstance().GetDeviceInfo(m_strDeviceID);
        }

        @Override
        public void CbShareInfoUpdatedCb(String a_strDeviceID, familyclient.java.device.cdm1.data.JShareInfoData a_dataShareInfo) {
            if (m_bRun && m_strDeviceID.equals(a_strDeviceID)) {
                if (a_dataShareInfo.m_iShareValue <= 0) {
                    m_listShareInfo.DelData(a_dataShareInfo.m_strShareFamilyID);
                } else {
                    JShareInfoData dataShareInfo = new JShareInfoData();
                    dataShareInfo.m_strShareFamilyID = a_dataShareInfo.m_strShareFamilyID;
                    dataShareInfo.m_iShareValue = a_dataShareInfo.m_iShareValue;
                    JFamilyManagerInterface.GetInstance().GetFamilyInfoByID(dataShareInfo.m_strShareFamilyID);
                    m_listShareInfo.AddData(dataShareInfo);
                }
                UpdateView();
            }
        }

        @Override
        public void CbShareInfoListUpdatedCb(String a_strDeviceID) {
            if (m_bRun && m_strDeviceID.equals(a_strDeviceID))
                JDevice_CDM1Interface.GetInstance().GetShareInfoList(m_strDeviceID);
        }

        @Override
        public void GetDeviceInfoCb(familyclient.java.device.cdm1.data.JDeviceInfoData a_dataDeviceInfo, String a_strErr) {
            if (!m_bRun)
                return;

            if (null != a_strErr && a_strErr.length() > 0) {
                Common.showToast(Common.MakeMsgByErr(FUNCTION, a_strErr));
            } else {
                if (m_strDeviceID.equals(a_dataDeviceInfo.m_strDeviceID)) {
                    m_strFamilyID = a_dataDeviceInfo.m_strFamilyID;
                    m_strDeviceName = a_dataDeviceInfo.m_strDeviceName;
                    m_dataMasterFamilyInfo.m_strFamilyID = m_strFamilyID;
                    JFamilyManagerInterface.GetInstance().GetFamilyInfoByID(m_strFamilyID);
                    UpdateView();
                }
            }
        }

        public void SetShareInfoCb(String a_strErr) {
            if (!m_bRun)
                return;

            if (null != a_strErr && a_strErr.length() > 0) {
                Common.showToast(Common.MakeMsgByErr(FUNCTION, a_strErr));
            } else {
                Common.showToast("分享成功");
            }
        }

        public void GetShareInfoListCb(familyclient.java.device.cdm1.data.JShareInfoListData a_listShareInfo, String a_strErr) {
            if (!m_bRun)
                return;

            if (null != a_strErr && a_strErr.length() > 0) {
                Common.showToast(Common.MakeMsgByErr(FUNCTION, a_strErr));
            } else {
                m_listShareInfo = new JShareInfoListData();
                for (int iIndex = 0; iIndex < a_listShareInfo.GetSize(); ++iIndex) {
                    JShareInfoData dataShareInfo = new JShareInfoData();
                    if (null != a_listShareInfo.GetData(iIndex)) {
                        dataShareInfo.m_strShareFamilyID = a_listShareInfo.GetData(iIndex).m_strShareFamilyID;
                        dataShareInfo.m_iShareValue = a_listShareInfo.GetData(iIndex).m_iShareValue;
                        JFamilyManagerInterface.GetInstance().GetFamilyInfoByID(dataShareInfo.m_strShareFamilyID);
                        m_listShareInfo.AddData(dataShareInfo);
                    }
                }
                UpdateView();
            }
        }

        public void ClearAllShareInfoCb(String a_strErr) {
            if (!m_bRun)
                return;

            if (null != a_strErr && a_strErr.length() > 0) {
                Common.showToast(Common.MakeMsgByErr(FUNCTION, a_strErr));
            } else {
                Common.showToast("清空分享成功");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sharelist);

        m_strDeviceID = getIntent().getStringExtra("DeviceID");

        JFamilyManagerInterface.GetInstance().AddListener(m_listenerFamilyManager);
        JDevice_CDM1Interface.GetInstance().AddListener(m_listenerCDM1);
        ImageView btBack = (ImageView) findViewById(R.id.iv_return);
        ImageView btAddShare = (ImageView) findViewById(R.id.iv_addshare);
        Button btClearAllShare = (Button) findViewById(R.id.clearallshare_bt);
        ListView lvShareList = (ListView) findViewById(R.id.sharelist);

        btBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBack();
            }
        });

        btAddShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Common.s_bDirectConnect) {
                    Common.showToast("直连模式不支持此功能");
                    return;
                }

                if (!m_strFamilyID.equals(Common.s_strFamilyID)) {
                    Common.showToast("无权限");
                    return;
                }

                Common.openEditTextInfoActivity(mActivity, 0, "", "", 0, "请输入ID分享设备");
                EditTextInfoActivity.setEditItemClickListener(new EditTextInfoActivity.OnEditItemClickListener() {
                    @Override
                    public void onEditItemClick(int requestCode, String a_strContent, String a_strParm) {
                        m_bRun = true;
                        BaseDevice.SetShareInfo(m_strDeviceID, a_strContent, 100);
                    }
                });
            }
        });

        btClearAllShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Common.s_bDirectConnect) {
                    Common.showToast("直连模式不支持此功能");
                    return;
                }

                if (!m_strFamilyID.equals(Common.s_strFamilyID)) {
                    Common.showToast("无权限");
                    return;
                }

                new AlertDialog(mActivity, "清空分享", "是否清空所有分享？", "", true, ALERT_DIALOG_CLEAR_ALL, m_OnDialogListener).show();
            }
        });

        lvShareList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (Common.s_bDirectConnect) {
                    Common.showToast("直连模式不支持此功能");
                    return true;
                }

                if (0 == position) {
                    return true;
                }

                ListView lvShareList = (ListView) findViewById(R.id.sharelist);
                Map<String, Object> mapItem = (Map<String, Object>) lvShareList.getItemAtPosition(position);
                String strShareFamilyID = (String) mapItem.get("FamilyID");
                JShareInfoData dataShareInfo = m_listShareInfo.GetData(strShareFamilyID);
                if (null == dataShareInfo) {
                    Common.showToast("找不到分享信息");
                    return true;
                }

                if (!Common.s_strFamilyID.equals(m_strFamilyID) && !Common.s_strFamilyID.equals(strShareFamilyID))
                    return true;

                String strFamilyInfo = dataShareInfo.m_strShareFamilyName;
                if (0 == strFamilyInfo.length())
                    strFamilyInfo = dataShareInfo.m_strShareFamilyPhone;
                if (0 == strFamilyInfo.length())
                    strFamilyInfo = dataShareInfo.m_strShareFamilyEmail;
                String strMessage = "是否删除";
                if (strFamilyInfo.length() > 0)
                    strMessage += "[" + strFamilyInfo + "]";
                else
                    strMessage += "分享者？";
                new AlertDialog(mActivity, "删除分享者", strMessage, strShareFamilyID, true, ALERT_DIALOG_DEL_SHARE, m_OnDialogListener).show();
                return true;
            }
        });
    }

    @Override
    protected void onDestroy() {
        JFamilyManagerInterface.GetInstance().DelListener(m_listenerFamilyManager);
        JDevice_CDM1Interface.GetInstance().DelListener(m_listenerCDM1);
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Refresh();
    }

    @Override
    public void onBackKey() {
        onBack();
    }

    public void onBack() {
        mActivity.finish();
    }

    public void Refresh() {
        BaseDevice.GetDeviceInfo(m_strDeviceID);
        BaseDevice.GetShareInfoList(m_strDeviceID);
    }

    public void UpdateView() {
        TextView tvDeviceName = (TextView) findViewById(R.id.device_name);
        TextView tvDeviceID = (TextView) findViewById(R.id.device_id);
        if (null == m_strDeviceID || 0 == m_strDeviceID.length())
            return;

        if (null == m_strDeviceName || 0 == m_strDeviceName.length())
            tvDeviceName.setText(m_strDeviceID);
        else
            tvDeviceName.setText(m_strDeviceName);
        tvDeviceID.setText(m_strDeviceID);

        if (null == m_listShareInfo)
            return;

        List<Map<String, Object>> listItems = new ArrayList<>();
        Map<String, Object> mapMasterItem = new HashMap<String, Object>();
        if (null == m_dataMasterFamilyInfo.m_strFamilyID)
            m_dataMasterFamilyInfo.m_strFamilyID = "";
        if (null == m_dataMasterFamilyInfo.m_strFamilyName)
            m_dataMasterFamilyInfo.m_strFamilyName = "";
        if (null == m_dataMasterFamilyInfo.m_strPhone)
            m_dataMasterFamilyInfo.m_strPhone = "";
        if (null == m_dataMasterFamilyInfo.m_strEmail)
            m_dataMasterFamilyInfo.m_strEmail = "";
        if (m_strFamilyID.equals(Common.s_strFamilyID))
            mapMasterItem.put("FamilyName", "自己/主人:" + m_dataMasterFamilyInfo.m_strFamilyName);
        else
            mapMasterItem.put("FamilyName", "主人:" + m_dataMasterFamilyInfo.m_strFamilyName);
        mapMasterItem.put("FamilyID", m_dataMasterFamilyInfo.m_strFamilyID);
        mapMasterItem.put("Sex", m_dataMasterFamilyInfo.m_iSex);
        mapMasterItem.put("Phone", m_dataMasterFamilyInfo.m_strPhone);
        mapMasterItem.put("Email", m_dataMasterFamilyInfo.m_strEmail);
        String strMasterFamilyInfo = "";
        if (JFamilyInfoData.s_iSex_Male == m_dataMasterFamilyInfo.m_iSex)
            strMasterFamilyInfo += "男";
        else if (JFamilyInfoData.s_iSex_Female == m_dataMasterFamilyInfo.m_iSex)
            strMasterFamilyInfo += "女";
        if (m_dataMasterFamilyInfo.m_strPhone.length() > 0) {
            if (strMasterFamilyInfo.length() > 0)
                strMasterFamilyInfo += ",";
            strMasterFamilyInfo += m_dataMasterFamilyInfo.m_strPhone;
        }
        if (m_dataMasterFamilyInfo.m_strEmail.length() > 0) {
            if (strMasterFamilyInfo.length() > 0)
                strMasterFamilyInfo += ",";
            strMasterFamilyInfo += m_dataMasterFamilyInfo.m_strEmail;
        }
        mapMasterItem.put("FamilyInfo", strMasterFamilyInfo);
        listItems.add(mapMasterItem);

        for (int iIndex = 0; iIndex < m_listShareInfo.GetSize(); ++iIndex) {
            JShareInfoData dataShareInfo = m_listShareInfo.GetData(iIndex);
            Map<String, Object> mapItem = new HashMap<String, Object>();
            if (dataShareInfo.m_strShareFamilyID.equals(Common.s_strFamilyID))
                mapItem.put("FamilyName", "自己:" + dataShareInfo.m_strShareFamilyName);
            else
                mapItem.put("FamilyName", dataShareInfo.m_strShareFamilyName);
            mapItem.put("FamilyID", dataShareInfo.m_strShareFamilyID);
            mapItem.put("Sex", dataShareInfo.m_iShareFamilySex);
            mapItem.put("Phone", dataShareInfo.m_strShareFamilyPhone);
            mapItem.put("Email", dataShareInfo.m_strShareFamilyEmail);

            String strFamilyInfo = "";
            if (JFamilyInfoData.s_iSex_Male == dataShareInfo.m_iShareFamilySex)
                strFamilyInfo += "男";
            else if (JFamilyInfoData.s_iSex_Female == dataShareInfo.m_iShareFamilySex)
                strFamilyInfo += "女";
            if (dataShareInfo.m_strShareFamilyPhone.length() > 0) {
                if (strFamilyInfo.length() > 0)
                    strFamilyInfo += ",";
                strFamilyInfo += dataShareInfo.m_strShareFamilyPhone;
            }
            if (dataShareInfo.m_strShareFamilyEmail.length() > 0) {
                if (strFamilyInfo.length() > 0)
                    strFamilyInfo += ",";
                strFamilyInfo += dataShareInfo.m_strShareFamilyEmail;
            }
            mapItem.put("FamilyInfo", strFamilyInfo);
            listItems.add(mapItem);
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems, R.layout.item_shareinfo,
                new String[]{"FamilyName", "FamilyInfo", "FamilyID", "Sex", "Phone", "Email"},
                new int[]{R.id.item_familyname, R.id.item_familyinfo, R.id.item_familyid, R.id.item_sex, R.id.item_phone, R.id.item_email});
        ListView list = (ListView) findViewById(R.id.sharelist);
        list.setAdapter(simpleAdapter);
    }

    private AlertDialog.OnDialogButtonClickListener m_OnDialogListener = new AlertDialog.OnDialogButtonClickListener() {
        @Override
        public void onDialogButtonClick(int requestCode, boolean isPositive, String a_strParam) {
            if (!isPositive)
                return;

            switch (requestCode) {
                case ALERT_DIALOG_DEL_SHARE:
                    BaseDevice.SetShareInfo(m_strDeviceID, a_strParam, -1);
                    break;
                case ALERT_DIALOG_CLEAR_ALL:
                    BaseDevice.ClearAllShareInfo(m_strDeviceID);
                    break;
                default:
                    break;
            }
        }
    };
}
